package com.xy.user.controller.adminuser;


import com.xy.core.page.Pagination;
import com.xy.core.utils.ConvertObj;
import com.xy.core.utils.UUIDUtils;
import com.xy.user.base.controller.BaseController;
import com.xy.user.domain.Xyrole;
import com.xy.user.domain.Xyuserrole;
import com.xy.user.service.XyroleService;
import com.xy.user.service.XyuserService;
import com.xy.user.service.XyuserroleService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 *   角色
 * Created by 汤伟杰 on 2017/5/23.
 */
@Controller
@RequestMapping("/xyrole")
public class XyroleController extends BaseController<Xyrole> {
    @Autowired
    private XyroleService xyroleService;

    /** 列表 **/
    @RequestMapping("/list.do")
    public String list(Integer pageNo, Integer pageSize, Xyrole xyrole, HttpServletRequest req, HttpServletResponse resp,
                       ModelMap model){
        setMsg(xyrole,req,model);
        if (pageNo == null) {
            pageNo = 1;
        }
        if (pageSize == null) {
            pageSize = 0;
        }
        try {
            Map<String, Object> params = ConvertObj.toMap(xyrole);
            Pagination pagination = xyroleService.list(pageNo.intValue(), pageSize.intValue(), params, model);
            model.addAttribute("pagination", pagination);
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("failed","获取角色列表失败!"+e.getMessage());
        }
        model.addAttribute("entity", xyrole);
        return "xyrole/list";
    }
    /**
    * api接口角色列表
    * @param pageNo
    * @param pageSize
    * @param xyrole
    * @param req
    * @param resp
    * @param model
    * @throws Exception
    */
    @RequestMapping("/apiList.jn")
    public void apiList(Integer pageNo, Integer pageSize, Xyrole xyrole,
        HttpServletRequest req, HttpServletResponse resp,
        ModelMap model) throws Exception {
        if (pageNo == null) {
            pageNo = 1;
        }
        if (pageSize == null) {
            pageSize = 0;
        }
        try {
            Map<String, Object> params = ConvertObj.toMap(xyrole);
            Pagination pagination = xyroleService.apilist(pageNo.intValue(), pageSize.intValue(), params, model);
            jsonResult(1,"","",pagination,resp);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult(0,"","获取角色列表失败!"+e,"",resp);
        }

    }
    /**
    * api接口角色详情
    * @param req
    * @param resp
    * @param model
    * @throws Exception
    */
    @RequestMapping("/apiDetail.jn")
    public void apiDetail(HttpServletRequest req, HttpServletResponse resp,
    ModelMap model) throws Exception {
        Map<String, Object> params = new HashMap<String, Object>();
        Enumeration<String> enumeration = req.getParameterNames();
        if(enumeration.hasMoreElements()){
            String next = enumeration.nextElement();
            params.put(next, req.getParameter(next));
        }

        try {
            Map<String,Object> result = xyroleService.getApiDetail(params);
            jsonResult(1,"","",result,resp);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult(0,"99","获取角色详情失败!"+e,"",resp);
        }

    }
    /** api测试页面 **/
    @RequestMapping("/apiTest.do")
    public String apiList(HttpServletRequest req, HttpServletResponse resp,
        ModelMap model) throws Exception {
        model.addAttribute("entity",new HashMap<String,Object>());
        return "xyrole/apiTest";

    }

    /** 保存 **/
    @RequestMapping("/save.do")
    public String save(Xyrole xyrole,
                      HttpServletRequest req, HttpServletResponse resp,
                       ModelMap model){
        try {

            if(StringUtils.isNotBlank(xyrole.getRoleId())){
                xyroleService.update(xyrole);


            }else{
                xyrole.setRoleId(UUIDUtils.getUUID());
                xyroleService.insert(xyrole);
            }
            model.addAttribute("success", "保存角色成功");
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("failed", "保存角色失败!详情："+e.getMessage());
        }
        return "redirect:list.do";
    }


    /** 详情 **/
    @RequestMapping("/detail.do")
    public String detail(@RequestParam(required = true)String roleId, Xyrole xyrole, HttpServletRequest req, HttpServletResponse resp,
                         ModelMap model){
        setMsg(xyrole,req,model);
        try {
            Xyrole entity = xyroleService.queryById(xyrole.getRoleId());
            model.addAttribute("entity", entity);
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("failed", "查询角色出错!详情："+e.getMessage());
        }
        return "xyrole/detail";
    }
    /** 新增或修改 **/
    @RequestMapping("/add.do")
    public String add(Xyrole xyrole, HttpServletRequest req, HttpServletResponse resp,
                       ModelMap model){
        setMsg(xyrole,req,model);
        if(StringUtils.isNotBlank(xyrole.getRoleId())){
            xyrole = xyroleService.queryById(xyrole.getRoleId());
            model.addAttribute("entity", xyrole);
        }
        return "xyrole/add";
    }
    /** 删除 **/
    @RequestMapping("/delete.do")
    public String delete(@RequestParam(required = true)String roleId,Xyrole xyrole, HttpServletRequest req, HttpServletResponse resp,
                     ModelMap model){
        try {
            xyroleService.deleteById(xyrole.getRoleId());
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("failed", e.getMessage());
        }
        return "redirect:list.do";
    }

    private void setMsg(Xyrole xyrole,HttpServletRequest req, ModelMap model) {
        model.addAttribute("failed", req.getParameter("failed"));
        model.addAttribute("success", req.getParameter("success"));
        model.addAttribute("entity", xyrole);
    }

    /**
     * 修改角色关联的用户页面
     * @param req
     * @param resp
     * @param model
     * @throws Exception
     */
    @RequestMapping("/updateuser.do")
    public String updateuser(@RequestParam(required = true) String roleId,
                           HttpServletRequest req, HttpServletResponse resp,
                          ModelMap model) throws Exception {
        //用户名username 是否有权限ispermission 用户id userId 角色roleId
        Map<String, Object> map = new HashMap<String, Object>();
        List<Map<String,Object>> listmap = xyuserService.allListpersimission(roleId);
        for (int i = 0; i < listmap.size(); i++) {
            if(listmap.get(i).get("roleId")!=null){
                listmap.get(i).put("ispermission",true);
            }else{
                listmap.get(i).put("ispermission",false);
            }
        }
//        0 = {HashMap$Node@6230} "roleId" -> "null"
//        1 = {HashMap$Node@6231} "ispermission" -> "true"
//        2 = {HashMap$Node@6232} "userId" -> "1"
//        3 = {HashMap$Node@6233} "username" -> "admin"
        model.addAttribute("listuser",listmap);//所有用户
        model.addAttribute("roleId",roleId);//所有用户
        return "xyrole/updateuser";
    }

    /**
     * 保存角色关联的用户
     * @param req
     * @param resp
     * @param model
     * @throws Exception
     */
    @RequestMapping("/saveuser.do")
    public void saveuser(@RequestParam(required = true) String roleId,

                         HttpServletRequest req, HttpServletResponse resp,
                          ModelMap model) throws Exception {
        List<Xyuserrole> list = xyuserroleService.queryByRoleId(roleId);//获取该角色所有关联用户
        List<String> listuserroleId = new ArrayList<String>();
        for (Xyuserrole xyuserrole : list) {
            listuserroleId.add(xyuserrole.getUserroleId());
        }
        String[] userIds = req.getParameterValues("userIds[]");
        List<String> userlist = new ArrayList<String>();
        if(userIds!=null&&userIds.length!=0){
            userlist = Arrays.asList(userIds);
        }


        List<Xyuserrole> savelist = new ArrayList<Xyuserrole>();
        for (String userId : userlist) {
            Xyuserrole xyuserrole = new Xyuserrole();
            xyuserrole.setUserId(userId);
            xyuserrole.setRoleId(roleId);
            xyuserrole.setUserroleId(UUIDUtils.getUUID());
            savelist.add(xyuserrole);
        }
        if(listuserroleId.size()!=0){
            xyuserroleService.deleteByIds(listuserroleId);
        }
        if(savelist.size()!=0){
            xyuserroleService.saves(savelist);
        }



    }

    @Autowired
    private XyuserService xyuserService;
    @Autowired
    private XyuserroleService xyuserroleService;


}
